from flask import Flask,request,jsonify
from flask import Blueprint
from getSql import getSql
from flask_jwt_extended import create_access_token,jwt_required,get_jwt_identity,verify_jwt_in_request
from pymysql.converters import escape_string
import time
import base64
import json
import hashlib
from utils import *

user = Blueprint('user',__name__)

@user.route('/login',methods=["POST"])
def login():
	try:
		username = request.json.get("username")
		password = request.json.get("password")
		if isEmpty(username):
			return jsonify({"msg": "请输入账号","code":400})
		if isEmpty(password):
			return jsonify({"msg": "请输入密码","code":400})	
		ip = request.remote_addr
		updateTime = getTime()
		cursor = getSql()
		sql = "select * from user where phone = %s and password = '%s'" % (username,password)
		cursor.execute(sql)
		data = cursor.fetchone()
		if data == None:
			return jsonify({"msg": "账号或密码错误","code":400})
		else:
			del data["token"]
			del data["password"]
			access_token = create_access_token(identity=data)
			updateSql = "update user set token = '%s' , ip = '%s' ,updateTime = %s where id = %s" % (access_token,ip,updateTime,data["id"])
			cursor.execute(updateSql)
			return jsonify({"msg": "登录成功","data":{"access_token":access_token},"code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})

@user.route('/info')
@jwt_required()
def info():
	try:
		user = get_jwt_identity()
		uid = user["id"]
		cursor = getSql()
		sql = "select * from user where id = %s" % (uid)
		cursor.execute(sql)
		data = cursor.fetchone()
		if data == None:
			return jsonify({"msg": "获取用户信息失败,用户不存在或者被删除","code":400})
		else:
			del data["password"]
			return jsonify({"msg": "获取用户信息成功","data":data,"code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})

@user.route('/editpass')
@jwt_required()
def editpass():
	try:
		user = get_jwt_identity()
		uid = user["id"]
		password = request.args.get("password")
		if isEmpty(password):
			return jsonify({"msg": "请输入密码","code":400})
		cursor = getSql()
		hasSql = "select * from user where id = %s" % (uid)
		cursor.execute(hasSql)
		ur = cursor.fetchone()
		if ur["password"] == password:
			return jsonify({"msg": "密码一致,修改失败","code":400})
		else:
			sql = "UPDATE user SET password = '%s' WHERE id = %s" % (password,uid)
			cursor.execute(sql)
			return jsonify({"msg": "操作成功","code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})